<template>
  <div class="article-management">
    <!-- 页面标题和操作栏 -->
    <div class="page-header">
      <h2 class="page-title">文章管理</h2>
      <div class="page-actions">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">添加文章</el-button>
        <el-input 
          placeholder="搜索文章标题" 
          v-model="searchForm.title" 
          class="search-input"
          prefix-icon="el-icon-search"
          clearable
          @clear="handleSearch"
          @keyup.enter.native="handleSearch"
        >
          <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
        </el-input>
      </div>
    </div>

    <!-- 高级搜索区域 -->
    <el-card shadow="hover" class="filter-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="分类">
          <el-select v-model="searchForm.categoryId" placeholder="全部分类" clearable>
            <el-option v-for="item in categoryOptions" :key="item.categoryId" :label="item.categoryName" :value="item.categoryId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="全部状态" clearable>
            <el-option label="发布" value="0"></el-option>
            <el-option label="草稿" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 文章列表表格 -->
    <el-card shadow="hover" class="table-card">
      <el-table 
        :data="articleList" 
        border 
        stripe 
        style="width: 100%" 
        v-loading="loading"
        class="article-table"
        :header-cell-style="{ backgroundColor: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column prop="articleId" label="文章ID" width="200" align="center"></el-table-column>
        <el-table-column prop="title" label="标题" width="200" show-overflow-tooltip align="center"></el-table-column>
        <el-table-column prop="categoryId" label="分类" width="150" align="center">
          <template slot-scope="scope">
            {{ categoryOptions.find(item => item.categoryId === scope.row.categoryId)?.categoryName }}
          </template>
        </el-table-column>
        <el-table-column prop="authorName" label="作者" width="150" align="center"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="createUser" label="创建人" width="180" align="center"></el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === '0' ? 'success' : 'info'">
              {{ scope.row.status === '0' ? '发布' : '草稿' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isRecommend" label="是否推荐" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isRecommend === '1' ? 'warning' : 'info'">
              {{ scope.row.isRecommend === '1' ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right" align="center">
          <template slot-scope="scope">
            <el-tooltip content="查看段落" placement="top">
              <el-button size="mini" icon="el-icon-view" @click="handleViewSections(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="编辑" placement="top">
              <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleEdit(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="发布" placement="top" v-if="scope.row.status === '1'">
              <el-button size="mini" type="success" icon="el-icon-check" @click="handlePublishFromList(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="取消发布" placement="top" v-else>
              <el-button size="mini" type="info" icon="el-icon-close" @click="handleUnpublishFromList(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        background
      >
      </el-pagination>
    </div>

    <!-- 文章编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="70%" :before-close="handleDialogClose">
      <el-form :model="articleForm" :rules="rules" ref="articleForm" label-width="100px" class="article-form">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="articleForm.title" placeholder="请输入文章标题"></el-input>
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="articleForm.categoryId" placeholder="请选择分类">
            <el-option v-for="item in categoryOptions" :key="item.categoryId" :label="item.categoryName" :value="item.categoryId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否推荐" prop="isRecommend">
          <el-radio-group v-model="articleForm.isRecommend">
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitArticleForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 文章段落管理对话框 -->
    <el-dialog title="文章段落管理" :visible.sync="sectionDialogVisible" width="80%" :before-close="handleSectionDialogClose">
      <div class="section-header">
        <div class="section-info">
          <h3 v-if="currentArticle">《{{ currentArticle.title }}》</h3>
          <el-tag v-if="currentArticle" :type="currentArticle.status === '0' ? 'success' : 'info'" style="margin-left: 10px;">
            {{ currentArticle.status === '0' ? '已发布' : '草稿' }}
          </el-tag>
        </div>
        <div class="section-actions">
          <el-button type="primary" icon="el-icon-plus" @click="handleAddSection">添加段落</el-button>
          <el-button 
            v-if="currentArticle && currentArticle.status === '1' && sectionList.length > 0" 
            type="success" 
            icon="el-icon-check" 
            @click="handlePublishArticle"
          >发布文章</el-button>
        </div>
      </div>

      <!-- 提示信息 -->
      <div class="section-tip" v-if="sectionList.length > 0">
        <i class="el-icon-info"></i>
        <span>段落将按照排序号从小到大排列显示。您可以通过修改排序号调整段落显示顺序。</span>
      </div>

      <el-table 
        :data="sectionList" 
        border 
        stripe 
        style="width: 100%" 
        v-loading="sectionLoading"
        :header-cell-style="{ backgroundColor: '#f5f7fa', color: '#606266' }"
        class="section-table"
        row-key="sectionId"
      >
        <el-table-column prop="sectionId" label="段落ID" width="200" align="center"></el-table-column>
        <el-table-column prop="sortOrder" label="排序" width="80" align="center"></el-table-column>
        <el-table-column prop="mediaType" label="媒体类型" width="120" align="center">
          <template slot-scope="scope">
            {{ getMediaTypeName(scope.row.mediaType) }}
          </template>
        </el-table-column>
        <el-table-column prop="mediaTitle" label="媒体标题" show-overflow-tooltip align="center">
          <template slot-scope="scope">

            {{ scope.row.mediaTitle || '-' }}
          </template>

        </el-table-column>
        <el-table-column prop="content" label="内容摘要" show-overflow-tooltip align="center">
          <template slot-scope="scope">
            <div v-html="getSummary(scope.row.content)"></div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template slot-scope="scope">
            <el-tooltip content="编辑" placement="top">
              <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleEditSection(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDeleteSection(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 段落编辑表单 -->
      <el-dialog
        width="70%"
        title="编辑段落"
        :visible.sync="sectionFormVisible"
        append-to-body
        :before-close="handleSectionFormClose">
        <el-form :model="sectionForm" :rules="sectionRules" ref="sectionForm" label-width="100px" class="section-form">
          <el-form-item label="排序" prop="sortOrder">
            <el-input-number v-model="sectionForm.sortOrder" :min="1" :max="999"></el-input-number>
          </el-form-item>
          <el-form-item label="媒体类型" prop="mediaType">
            <el-radio-group v-model="sectionForm.mediaType">
              <el-radio label="0">图片</el-radio>
              <el-radio label="1">视频</el-radio>
              <el-radio label="2">纯文本</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="媒体标题" prop="mediaTitle" v-if="sectionForm.mediaType !== '2'">
            <el-input v-model="sectionForm.mediaTitle" placeholder="请输入媒体标题"></el-input>
          </el-form-item>
          <el-form-item label="媒体文件" prop="mediaUrl" v-if="sectionForm.mediaType === '0'">
            <el-upload
              class="media-uploader"
              action="http://localhost:9002/api/system/image/articleImage"
              :show-file-list="false"
              :on-success="handleImageSuccess"
              :before-upload="beforeImageUpload">
              <img v-if="sectionForm.mediaUrl" :src="sectionForm.mediaUrl" class="media-image">
              <div v-else class="upload-placeholder">
                <i class="el-icon-picture-outline"></i>
                <div>点击上传图片</div>
              </div>
            </el-upload>
            <div class="upload-tip">支持JPG、PNG格式，不超过4MB</div>
          </el-form-item>
          <el-form-item label="媒体文件" prop="mediaUrl" v-if="sectionForm.mediaType === '1'">
            <el-upload
              class="media-uploader video-uploader"
              action="http://localhost:9002/api/system/image/articleVideo"
              :show-file-list="false"
              :on-success="handleVideoSuccess"
              :before-upload="beforeVideoUpload">
              <div v-if="sectionForm.mediaUrl" class="video-container">
                <div class="video-name">{{ sectionForm.mediaTitle || '未命名视频' }}</div>
                <video :src="sectionForm.mediaUrl" class="video-preview" controls></video>
                <div class="video-upload-tip">视频已上传，可以点击上方播放</div>
              </div>
              <div v-else class="upload-placeholder">
                <i class="el-icon-video-camera"></i>
                <div>点击上传视频</div>
              </div>
            </el-upload>
            <div class="upload-tip">支持MP4、AVI等格式，不超过50MB</div>
          </el-form-item>
          <el-form-item label="段落内容" prop="content">
            <el-input type="textarea" v-model="sectionForm.content" :rows="10" placeholder="请输入段落内容"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="sectionFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitSectionForm">确 定</el-button>
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import service from '@/utils/request'

export default {
  name: 'ArticleManagement',
  data() {
    return {
      // 搜索表单
      searchForm: {
        articleId: '',
        title: '',
        categoryId: '',
        status: ''
      },
      // 分页信息
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      // 文章列表
      articleList: [],
      loading: false,
      // 分类选项
      categoryOptions: [],
      // 作者选项
      authorOptions: [],
      // 文章编辑对话框
      dialogVisible: false,
      dialogTitle: '新增文章',
      articleForm: this.initArticleForm(),
      rules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ],
        authorId: [
          { required: true, message: '请选择作者', trigger: 'change' }
        ]
      },
      // 段落管理
      sectionDialogVisible: false,
      currentArticleId: '',
      currentArticle: null,
      sectionList: [],
      sectionLoading: false,
      // 段落编辑表单
      sectionFormVisible: false,
      sectionForm: this.initSectionForm(),
      sectionRules: {
        sortOrder: [
          { required: true, message: '请输入排序号', trigger: 'blur' }
        ],
        mediaType: [
          { required: true, message: '请选择媒体类型', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入段落内容', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.fetchArticleList();
    this.fetchCategoryOptions();
  },
  methods: {
    // 初始化文章表单
    initArticleForm() {
      return {
        articleId: '',
        title: '',
        categoryId: '',
        articleName: '',
        createTime: '',
        createUser: '',
        updateTime: '',
        updateUser: '',
        status: '1', // 默认为草稿状态
        isRecommend: '0',
        token: localStorage.getItem('token')
      };
    },
    // 初始化段落表单
    initSectionForm() {
      return {
        sectionId: '',
        articleId: '',
        sortOrder: 1,
        mediaType: '2', // 默认纯文本
        mediaTitle: '',
        mediaUrl: '',
        content: ''
      };
    },
    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '';
      const date = new Date(dateTime);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
    },
    // 获取媒体类型名称
    getMediaTypeName(type) {
      const typeMap = {
        '0': '图片',
        '1': '视频',
        '2': '纯文本'
      };
      return typeMap[type] || '未知';
    },
    // 获取内容摘要
    getSummary(content) {
      if (!content) return '';
      return content.length > 50 ? content.substring(0, 50) + '...' : content;
    },
    // 获取文章列表
    async fetchArticleList() {
      this.loading = true;
      try {
        const params = {
          pageNum: this.page.currentPage,
          pageSize: this.page.pageSize,
          title: this.searchForm.title,
          categoryId: this.searchForm.categoryId,
          status: this.searchForm.status,
          token:''
        };
        
        // 判断当前用户角色是否为戏曲家(roleid为3)
        const roleId = localStorage.getItem('roletype');
        if (roleId === '3') {
          // 如果是戏曲家，则只查询该用户创建的文章
          const token = localStorage.getItem('token');
          params.token = token;
        }
        
        const res = await service.get('/api/study/article/getArticleList', { params });
        
        if (res.code === 200) {
          console.log(res.data);
          this.articleList = res.data.list || [];
          this.page.total = res.data.total || 0;
        } else {
          this.$message.error(res.message || '获取文章列表失败');
        }
        this.loading = false;
      } catch (error) {
        console.error('获取文章列表失败', error);
        this.$message.error('获取文章列表失败，请稍后重试');
        this.loading = false;
      }
    },
    // 获取分类选项
    async fetchCategoryOptions() {
      try {
        const res = await service.get('/api/study/category/getAllCategory');
        
        if (res.code === 200) {
          console.log(res.data);
          this.categoryOptions = (res.data || []).map(item => ({
            categoryId: item.categoryId,
            categoryName: item.categoryName
          }));
        } else {
          this.$message.error(res.message || '获取分类选项失败');
        }
      } catch (error) {
        console.error('获取分类选项失败', error);
        this.$message.error('获取分类选项失败，请稍后重试');
      }
    },
    // 获取文章段落列表
    async fetchSectionList(articleId) {
      this.sectionLoading = true;
      try {
        const res = await service.get(`/api/study/section/getSectionList/${articleId}`);
        
        if (res.code === 200) {
          this.sectionList = res.data || [];
          // 对段落按排序号排序
          this.sectionList.sort((a, b) => a.sortOrder - b.sortOrder);
        } else {
          this.$message.error(res.message || '获取文章段落列表失败');
        }
        this.sectionLoading = false;
      } catch (error) {
        console.error('获取文章段落列表失败', error);
        this.$message.error('获取文章段落列表失败，请稍后重试');
        this.sectionLoading = false;
      }
    },
    // 处理查询
    handleSearch() {
      this.page.currentPage = 1;
      this.fetchArticleList();
    },
    // 重置查询条件
    resetSearch() {
      this.searchForm = {
        title: '',
        categoryId: '',
        status: ''
      };
      this.handleSearch();
    },
    // 处理分页大小变化
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.fetchArticleList();
    },
    // 处理当前页变化
    handleCurrentChange(val) {
      this.page.currentPage = val;
      this.fetchArticleList();
    },
    // 添加文章
    handleAdd() {
      this.dialogTitle = '新增文章';
      this.articleForm = this.initArticleForm();
      this.dialogVisible = true;
    },
    // 编辑文章
    handleEdit(row) {
      // 如果文章已发布，需要先提示用户将转为草稿才能编辑
      if (row.status === '0') {
        this.$confirm('该文章已发布，编辑将会将文章状态变更为草稿，可能导致前台暂时无法查看该文章，是否继续？', '警告', {
          confirmButtonText: '继续编辑',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.dialogTitle = '编辑文章';
          this.articleForm = { ...row };
          // 强制设置为草稿状态
          this.articleForm.status = '1';
          this.articleForm.token = localStorage.getItem('token');
          this.dialogVisible = true;
        }).catch(() => {
          this.$message.info('已取消编辑');
        });
      } else {
        this.dialogTitle = '编辑文章';
        this.articleForm = { ...row };
        this.articleForm.token = localStorage.getItem('token');
        this.dialogVisible = true;
      }
    },
    // 删除文章
    handleDelete(row) {
      this.$confirm('确认删除该文章吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await service.delete(`/api/study/article/deleteArticle/${row.articleId}`);
          
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.fetchArticleList();
          } else {
            this.$message.error(res.message || '删除失败');
          }
        } catch (error) {
          console.error('删除文章失败', error);
          this.$message.error('删除文章失败，请稍后重试');
        }
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    // 提交文章表单
    submitArticleForm() {
      this.$refs.articleForm.validate(async (valid) => {
        if (valid) {
          try {
            // 强制设置为草稿状态
            this.articleForm.status = '1';
            
            let res;
            if (this.articleForm.articleId) {
              res = await service.put('/api/study/article/updateArticle', this.articleForm);
            } else {
              res = await service.post('/api/study/article/addArticle', this.articleForm);
            }
            
            if (res.code === 200) {
              this.$message.success('保存成功');
              this.dialogVisible = false;
              
              // 如果是新增文章，提示用户添加段落
              if (!this.articleForm.articleId) {
                this.$confirm('文章已创建为草稿状态，是否立即添加段落内容？', '提示', {
                  confirmButtonText: '是',
                  cancelButtonText: '稍后添加',
                  type: 'info'
                }).then(() => {
                  // 查找刚刚创建的文章
                  this.fetchArticleList();
                  setTimeout(() => {
                    const newArticle = this.articleList.find(item => item.title === this.articleForm.title);
                    if (newArticle) {
                      this.handleViewSections(newArticle);
                    }
                  }, 1000);
                }).catch(() => {
                  // 用户选择稍后添加
                  this.fetchArticleList();
                });
              } else {
                this.fetchArticleList();
              }
            } else {
              this.$message.error(res.message || '保存失败');
            }
          } catch (error) {
            console.error('保存文章失败', error);
            this.$message.error('保存文章失败，请稍后重试');
          }
        } else {
          return false;
        }
      });
    },
    // 关闭对话框
    handleDialogClose(done) {
      this.$confirm('确认关闭？未保存的数据将会丢失', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        done();
      }).catch(() => {});
    },
    // 查看文章段落
    handleViewSections(row) {
      this.currentArticleId = row.articleId;
      this.currentArticle = row;
      this.fetchSectionList(row.articleId);
      this.sectionDialogVisible = true;
    },
    // 关闭段落管理对话框
    handleSectionDialogClose(done) {
      done();
    },
    // 添加段落
    handleAddSection() {
      // 查找当前最大排序号
      let maxSortOrder = 0;
      if (this.sectionList && this.sectionList.length > 0) {
        // 遍历列表找出最大排序号
        for (const section of this.sectionList) {
          if (section.sortOrder > maxSortOrder) {
            maxSortOrder = parseInt(section.sortOrder);
          }
        }
      }
      
      // 初始化表单，并设置排序号为最大值+1
      this.sectionForm = this.initSectionForm();
      this.sectionForm.articleId = this.currentArticleId;
      this.sectionForm.sortOrder = maxSortOrder + 1;
      this.sectionFormVisible = true;
    },
    // 编辑段落
    handleEditSection(row) {
      this.sectionForm = { ...row };
      this.sectionFormVisible = true;
    },
    // 删除段落
    handleDeleteSection(row) {
      this.$confirm('确认删除该段落吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await service.delete(`/api/study/section/deleteSection/${row.sectionId}`);
          
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.fetchSectionList(this.currentArticleId);
          } else {
            this.$message.error(res.message || '删除失败');
          }
        } catch (error) {
          console.error('删除段落失败', error);
          this.$message.error('删除段落失败，请稍后重试');
        }
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    // 提交段落表单
    submitSectionForm() {
      this.$refs.sectionForm.validate(async (valid) => {
        if (valid) {
          try {
            let res;
            if (this.sectionForm.sectionId) {
              res = await service.put('/api/study/section/updateSection', this.sectionForm);
            } else {
              res = await service.post('/api/study/section/addSection', this.sectionForm);
            }
            
            if (res.code === 200) {
              this.$message.success('保存成功');
              this.sectionFormVisible = false;
              await this.fetchSectionList(this.currentArticleId);
              // 重新按排序号排序
              this.sectionList.sort((a, b) => a.sortOrder - b.sortOrder);
            } else {
              this.$message.error(res.message || '保存失败');
            }
          } catch (error) {
            console.error('保存段落失败', error);
            this.$message.error('保存段落失败，请稍后重试');
          }
        } else {
          return false;
        }
      });
    },
    // 发布文章
    handlePublishArticle() {
      if (!this.currentArticle || this.currentArticle.status !== '1') {
        return;
      }
      
      if (this.sectionList.length === 0) {
        this.$message.warning('文章至少需要一个段落才能发布');
        return;
      }
      
      this.$confirm('确认发布该文章吗？发布后将对所有用户可见', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const articleData = {
            articleId: this.currentArticle.articleId,
            status: '0', // 发布状态
            token: localStorage.getItem('token')
          };
          
          const res = await service.put('/api/study/article/updateArticle', articleData);
          
          if (res.code === 200) {
            this.$message.success('文章发布成功');
            // 更新当前文章对象的状态
            this.currentArticle.status = '0';
            // 刷新文章列表
            this.fetchArticleList();
          } else {
            this.$message.error(res.message || '发布失败');
          }
        } catch (error) {
          console.error('发布文章失败', error);
          this.$message.error('发布文章失败，请稍后重试');
        }
      }).catch(() => {
        this.$message.info('已取消发布');
      });
    },
    // 关闭段落编辑表单
    handleSectionFormClose(done) {
      this.$confirm('确认关闭？未保存的数据将会丢失', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        done();
      }).catch(() => {});
    },
    // 上传媒体文件方法替换为新的处理函数
    // 处理图片上传成功
    handleImageSuccess(res) {
      if (res.code === 200) {
        this.sectionForm.mediaUrl = res.data || res.url;
        this.$message.success('图片上传成功');
      } else {
        this.$message.error(res.message || '图片上传失败');
      }
    },
    
    // 图片上传前的验证
    beforeImageUpload(file) {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt4M = file.size / 1024 / 1024 < 4;
      
      if (!isImage) {
        this.$message.error('只能上传JPG或PNG格式的图片!');
      }
      if (!isLt4M) {
        this.$message.error('图片大小不能超过4MB!');
      }
      
      return isImage && isLt4M;
    },
    
    // 处理视频上传成功
    handleVideoSuccess(res) {
      if (res.code === 200) {
        this.sectionForm.mediaUrl = res.data || res.url;
        this.$message.success('视频上传成功');
      } else {
        this.$message.error(res.message || '视频上传失败');
      }
    },
    
    // 视频上传前的验证
    beforeVideoUpload(file) {
      const isValidFormat = ['video/mp4', 'video/avi', 'video/quicktime'].includes(file.type);
      const isLt50M = file.size / 1024 / 1024 < 50;
      
      if (!isValidFormat) {
        this.$message.error('只能上传MP4、AVI或MOV格式的视频!');
      }
      if (!isLt50M) {
        this.$message.error('视频大小不能超过50MB!');
      }
      
      return isValidFormat && isLt50M;
    },
    
    // 发布文章（从列表中）
    async handlePublishFromList(row) {
      // 先检查文章是否有段落内容
      try {
        this.loading = true;
        const res = await service.get(`/api/study/section/getSectionList/${row.articleId}`);
        this.loading = false;
        
        if (res.code === 200) {
          const sections = res.data || [];
          if (sections.length === 0) {
            // 提示用户添加段落
            this.$confirm('文章需要添加段落内容才能发布，是否立即添加段落?', '提示', {
              confirmButtonText: '是',
              cancelButtonText: '稍后添加',
              type: 'info'
            }).then(() => {
              this.handleViewSections(row);
            }).catch(() => {});
            return;
          }
          
          // 如果有段落内容，确认发布
          this.$confirm('确认发布该文章吗？发布后将对所有用户可见', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            try {
              const articleData = {
                articleId: row.articleId,
                status: '0', // 发布状态
                token: localStorage.getItem('token')
              };
              
              const updateRes = await service.put('/api/study/article/updateArticleStatus', articleData);
              
              if (updateRes.code === 200) {
                this.$message.success('文章发布成功');
                // 刷新文章列表
                this.fetchArticleList();
              } else {
                this.$message.error(updateRes.message || '发布失败');
              }
            } catch (error) {
              console.error('发布文章失败', error);
              this.$message.error('发布文章失败，请稍后重试');
            }
          }).catch(() => {
            this.$message.info('已取消发布');
          });
        } else {
          this.$message.error(res.message || '获取文章段落列表失败');
        }
      } catch (error) {
        this.loading = false;
        console.error('获取文章段落列表失败', error);
        this.$message.error('获取文章段落列表失败，请稍后重试');
      }
    },
    
    // 取消发布文章（从列表中）
    handleUnpublishFromList(row) {
      this.$confirm('确认取消发布该文章吗？取消后前台将无法查看该文章', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const articleData = {
            articleId: row.articleId,
            status: '1', // 草稿状态
            token: localStorage.getItem('token')
          };
          
          const res = await service.put('/api/study/article/updateArticleStatus', articleData);
          
          if (res.code === 200) {
            this.$message.success('文章已转为草稿状态');
            // 刷新文章列表
            this.fetchArticleList();
          } else {
            this.$message.error(res.message || '取消发布失败');
          }
        } catch (error) {
          console.error('取消发布文章失败', error);
          this.$message.error('取消发布文章失败，请稍后重试');
        }
      }).catch(() => {
        this.$message.info('已取消操作');
      });
    }
  }
};
</script>

<style scoped>
.article-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  font-size: 22px;
  font-weight: bold;
  color: #303133;
  margin: 0;
}

.page-actions {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 250px;
}

.filter-card {
  margin-bottom: 20px;
}

.search-form {
  padding: 5px 0;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-info {
  display: flex;
  align-items: center;
}

.section-info h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.section-actions {
  display: flex;
  gap: 10px;
}

/* 表单样式优化 */
.article-form .el-form-item,
.section-form .el-form-item {
  margin-bottom: 22px;
}

/* 表格样式优化 */
.article-table th,
.section-table th {
  background-color: #f5f7fa;
  color: #606266;
}

.article-table tr:hover,
.section-table tr:hover {
  background-color: #f5f7fa;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .page-actions {
    margin-top: 10px;
    width: 100%;
    flex-wrap: wrap;
  }
  
  .search-input {
    width: 100%;
    margin-top: 10px;
  }
}

/* 媒体上传样式 */
.media-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 300px;
  height: 200px;
  margin-bottom: 10px;
  transition: border-color 0.3s;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fafafa;
}

.media-uploader:hover {
  border-color: #409EFF;
}

.media-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #8c939d;
  width: 100%;
  height: 100%;
}

.upload-placeholder i {
  font-size: 48px;
  margin-bottom: 10px;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
  line-height: 1.4;
}

/* 视频上传器样式 */
.video-uploader {
  height: 240px;
  width: 400px;
}

.video-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: rgba(245, 247, 250, 0.8);
  border-radius: 4px;
  padding: 10px;
  overflow: hidden;
}

.video-preview {
  width: 100%;
  height: 160px;
  object-fit: contain;
  background-color: #000;
  border-radius: 4px;
}

.video-name {
  font-size: 14px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
  text-align: center;
}

.video-upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  text-align: center;
}

.section-tip {
  background-color: #f0f9eb;
  padding: 10px 15px;
  border-radius: 4px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #67c23a;
}

.section-tip i {
  margin-right: 8px;
  font-size: 16px;
}
</style>
